/* dp : Data Provider */
/*
	Steps :
	- Open connection 
	- execute some performance
	- close connection
	
	Main scenario function 
	 - createConnection(dbName)
	 - insert(collection, data) 
	 - delete(collection, conditionValues)
	 - update(collection, conditionValues, data)
	
	- getData(conditionValues) only  return json object {value:"1"}
*/

var MongoClient = require('mongodb').MongoClient
  , assert = require('assert');

// Connection URL
var url = 'mongodb://localhost:27017/demo';
var mode = "developer";
var connectTest = function(callback){
	MongoClient.connect(url, function(err, db) {	
		var result = 1;
		if(err){
			//throw err
			var msg = 'server not found' + JSON.stringify(err);
			console.log(msg);
			//console(err);
			if(mode == "developer"){
				result = {status:false, msg:msg};
			}
			else{
				result = {status:false, msg:"Mongo db server not found. Connect fail"} ;
			}
		}
		else{
			//console(err);
			
			console.log("Connected correctly to mongodb server");
			result = {status:true, msg:"Connected correctly to Mongodb server"} ;
			db.close();
		}
		callback(result);
	});
}
var connectTest1 = function(callback){
	MongoClient.connect(url, function(err, db) {	
		if(err) throw err;
		console.log("Connected correctly to mongodb server");
		var result = {status:true, msg:"Connected correctly to Mongodb server"} ;
		callback(result);
		db.close();
	});
}
var connect = function(callback){
	MongoClient.connect(url, function(err, db) {
		var result = {status:true, msg:"Connected correctly to Mongodb server"} ;
		if(err){
			//throw err
			console.log("Server not found " + err);
			if(mode == "developer"){
				var result = {status:false, msg:err} ;
				result["msg"] = err;
			}
			else{
				var result = {status:false, msg:"db server not found. Connect fail"} ;
			}
		}
		else{
			console.log("Connected correctly to mongodb server");
			//db.close();
		}
		callback(result,db);
	});
}
var insertDocuments = function() {
  // Get the documents collection
	MongoClient.connect(url, function(err, db) {
		assert.equal(null, err);
		var collection = db.collection('documents');
		// Insert some documents
		collection.insert([
		{a : 1}, {a : 2}, {a : 3}
		], function(err, result) {
			assert.equal(err, null);
			assert.equal(3, result.result.n);
			assert.equal(3, result.ops.length);
			console.log("Inserted 3 documents into the document collection");
			callback(result);
		});
		db.close();
	});
}

var insert1 = function(docName, data) {
	// Use connect method to connect to the Server
	MongoClient.connect(url, function(err, db) {
		assert.equal(null, err);
		console.log("Connected - for inserting...");		
		// begin insert 
		// Get the documents collection
		console.log(data);
		var collection = db.collection(docName);
		// Insert some documents
		collection.insert(data, function(err, result) {
			assert.equal(err, null);
			assert.equal(3, result.result.n);
			assert.equal(3, result.ops.length);
			console.log("Inserted ! ");
			//callback(result);
		});
		db.close();
	});
}
var insertok = function(docName, data, callback) {
	// Use connect method to connect to the Server
	MongoClient.connect(url, function(err, db) {
		//assert.equal(null, err);
		console.log("Connected and Inserting...");		
		// Get the documents collection
		console.log(data);
		var collection = db.collection(docName);
		// Insert some documents
		collection.insert(data, function(err, result) {
			//assert.equal(err, null);
			//assert.equal(3, result.result.n);
			//assert.equal(3, result.ops.length);
			result = data;
			console.log("Inserted !");
			callback(result);
		});
		db.close();
	});
}

var insert = function(collectionName, data, callback) {
	connect(function(result,db){
		if(result.status){
			var collection = db.collection(collectionName);
			console.log('Inserting data :');
			console.log(data);
			console.log('to "' + collectionName + '" collection');
			collection.insert(data, function(err, result) {
				if(err){
					result = data;
					console.log(data);	
					console.log("Insert successfully!");				
					callback(result);
				}
				else{
					if(mode != "developer"){
						console.log(err);
						callback(err);
					}
					else{
						// check collection name						
						/*var collections = db.getCollections();
						if(collections.indexOf(collectionName) != -1){
							var msg = 'collection name not exists !';
							console.log(msg);
							callback(msg);	
						}*/
						console.log(err);
						callback(err);
					}
				}
			});
			db.close();
		}
		else{			
			console.log("Error !!! Can't insert data");
			callback(result);
		}
	});
}

var updateUser = function(collectionName, query, update, callback){
	connect(function(result,db){
		if(result.status){
			var collection = db.collection(collectionName);
			/*
				query  = {id:3};
				update = {$set:{status:"onleline"}}
			*/
			console.log('Updating data :');
			console.log('update ' + JSON.stringify(update) + ' to "' + collectionName + '" collection where '+ JSON.stringify(query));
			
		  collection.update(query, update, function(err,result){
				if(err) {					
					result = 'update ' + JSON.stringify(update) + ' to "' + collectionName + '" collection where '+ JSON.stringify(query) + ' successfully';
					console.log("success");
				}
				else {
					console.log("failed")
					result = "insert failed"
				}
				callback(result);
		  });
		  db.close();
		}
		else{			
			console.log("Error !!! Can't update data");
			callback(result);
		}
	});		
}

var deleteUser = function(collectionName, query, callback){
	connect(function(result,db){
		if(result.status){
			var collection = db.collection(collectionName);			
			console.log('Updating data :');
			console.log('remove document' + JSON.stringify(update) + ' to "' + collectionName + '" collection where '+ JSON.stringify(query));
			
		  collection.update(query, update, function(err,result){
				if(err) {
					console.log("success");
					result = 'update ' + JSON.stringify(update) + ' to "' + collectionName + '" collection where '+ JSON.stringify(query) + ' successfully';
				}
				else {
					console.log("failed")
					result = "insert failed"
				}
				callback(result);
		  });
		  db.close();
		}
		else{			
			console.log("Error !!! Can't update data");
			callback(result);
		}
	});		
}

var getUser = function(collectionName, query, callback){
	connect(function(result,db){
		if(result.status){
			var collection = db.collection(collectionName);			
			collection.find({}).nextObject(function(err,docs){
				if(err){					
					console.log('finding records have ' + JSON.stringify(query) + ' in ' + collectionName + '...');
					//console.dir(docs);
					//console.log(docs);
					//assert.equal(2, docs.length);
					//console.dir(docs)
					//callback(docs);
					for(var i in docs) {
						console(i);
						callback(i);
					}
				}
				else {
					console.log("Not found");
					docs = "Not found"
				}
				//callback(docs);
			});
			
			//console.log('finding records have ' + JSON.stringify(query) + ' in ' + collectionName + '...');
			//var docs = collection.find({},{explain:true});
			//console.log(docs);
			//callback(docs); // error
			
			db.close();
		}
		else{			
			console.log("Error connect mongodb");
			callback(docs);
		}
	});
}

var deleteUser = function(collectionName, query, callback){
	connect(function(result,db){
		if(result.status){
			var collection = db.collection(collectionName);			
			collection.remove(query,function(err, result){
				if(err) {
					var msg = 'deleted records have ' + JSON.stringify(query) + ' in ' + collectionName;
					console.log(msg);				
				}
				else {
					console.log("Not found");
				}
				callback(msg);
			});
			db.close();
		}
		else{			
			console.log("Error connect mongodb");
			callback("error");
		}
	});
}
var viewDocuments = function(collectionName, query, callback){
	MongoClient.connect('mongodb://127.0.0.1:27017/demo', function(err, db) {
		if(err) throw err;	 
		var collection = db
		  .collection(collectionName)
		  .find(query,{username:0})
		  .limit(10)
		  .toArray(function(err, docs) {
			console.dir(docs);
			callback(docs);
		});
	});	
}
